Skip to content
This repository was archived by the owner on Oct 10, 2025. It is now read-only.

Conversation

josecelano
Copy link
Member

Summary

This PR implements automated MySQL database backup functionality as part of Phase 3 of Issue #21 (Complete Application Installation Automation). This phase focuses on backup automation, laying the foundation for subsequent SSL automation work.

🎯 What's Implemented

Core Backup Automation

  • MySQL Backup Script (application/share/bin/mysql-backup.sh)
    • Full database backup with compression (gzip)
    • Configurable retention policy (default: 7 days)
    • Comprehensive logging with timestamps
    • Error handling and validation
    • Non-interactive operation for automation

Infrastructure Integration

  • Deployment Integration in infrastructure/scripts/deploy-app.sh
    • setup_backup_automation() function
    • Automated cron job installation
    • Environment-aware configuration
    • Part of the standard deployment workflow

Configuration Management

  • Environment Variables added to configuration templates
    • ENABLE_DB_BACKUPS (boolean) - Enable/disable backup automation
    • BACKUP_RETENTION_DAYS (integer) - Number of days to retain backups
  • Default Settings - Backups enabled by default in local development
  • Template Updates - All environment templates include backup variables

Documentation & Testing

🧪 Testing Performed

Automated Testing

  • CI Pipeline: All linting and unit tests pass
  • Infrastructure Tests: Terraform validation, cloud-init syntax
  • Application Tests: Docker Compose validation, script syntax

Manual Testing (Comprehensive)

  • End-to-End Deployment: Full infrastructure + application deployment
  • Backup Script Execution: Manual and automated backup creation
  • Backup Content Validation: Schema inspection, data completeness
  • Cron Job Integration: Automated backup scheduling and execution
  • Log File Validation: Proper logging and error reporting
  • Retention Policy: Old backup cleanup verification

Backup Content Verification

-- Verified backup contains complete schema and data
SHOW TABLES;        -- ✅ All tracker tables present
SELECT COUNT(*) FROM torrust_tracker_keys;  -- ✅ Data preserved
-- Full restoration capability confirmed

🏗️ Twelve-Factor Architecture Compliance

This implementation maintains strict twelve-factor app principles:

  • Config: Environment variables for all settings
  • Build/Release/Run: Clear separation maintained
  • Backing Services: MySQL treated as attached resource
  • Processes: Stateless backup script design
  • Logs: Structured logging to files and stdout

🔧 Configuration

Enable Backup Automation

# In environment files (.env, local.env, production.env)
ENABLE_DB_BACKUPS=true
BACKUP_RETENTION_DAYS=7

Backup Storage

  • Location: /home/torrust/backups/mysql/
  • Format: tracker_backup_YYYY-MM-DD_HH-MM-SS.sql.gz
  • Retention: Configurable (default: 7 days)

🚀 Deployment Impact

For Existing Deployments

  • Non-Breaking: Backup automation is opt-in via environment variables
  • Default Disabled: Production environments need explicit enablement
  • Resource Usage: Minimal disk space and CPU impact

For New Deployments

  • Enabled by Default: Local development environments
  • Zero Configuration: Works out-of-the-box with sensible defaults
  • Production Ready: Full error handling and logging

📋 Migration Notes

Environment Configuration

When deploying this update:

  1. Review backup settings in your environment configuration
  2. Enable backups if desired: ENABLE_DB_BACKUPS=true
  3. Adjust retention if needed: BACKUP_RETENTION_DAYS=14
  4. Deploy normally - backup setup is automatic

Storage Requirements

  • Backup Size: ~10-50KB for typical tracker databases
  • Daily Growth: Minimal for tracker data
  • Monitoring: Check /home/torrust/backups/mysql/ periodically

🔄 What's Next (Post-Merge)

This PR completes Phase 3 of Issue #21. The next phase will implement:

  • SSL Certificate Automation (Let's Encrypt integration)
  • Certificate Renewal Automation (Automatic renewal scripts)
  • Production SSL Configuration (Nginx HTTPS setup)

🛡️ Security Considerations

  • Access Control: Backup files have restricted permissions (600)
  • Data Protection: Backups contain sensitive tracker data
  • Log Security: No sensitive information logged
  • Process Isolation: Backup runs as torrust user

📝 Files Changed

New Files

  • application/share/bin/mysql-backup.sh - Main backup script
  • docs/guides/database-backup-testing-guide.md - Testing documentation

Modified Files

  • infrastructure/scripts/deploy-app.sh - Backup automation integration
  • infrastructure/config/environments/local.env - Local environment config
  • infrastructure/config/environments/local.defaults - Local defaults
  • infrastructure/config/templates/docker-compose.env.tpl - Environment template
  • docs/issues/21-complete-application-installation-automation.md - Progress tracking

Ready for Review
All tests pass, documentation is complete, and the feature is fully functional.


Part of Issue #21: Complete Application Installation Automation
Phase: 3 - Database Backup Automation
Next Phase: SSL Certificate Automation

- Create detailed implementation plan for Phase 3: Maximum Practical Application Installation Automation
- Document current state analysis with accurate status of implemented vs missing components
- Provide technical implementation details for SSL certificate automation and MySQL backup automation
- Include testing strategy with unit, integration, SSL workflow, and end-to-end testing approaches
- Define success criteria focusing on 90%+ automation with minimal manual steps
- Add risk assessment and mitigation strategies for high-risk areas
- Establish timeline and dependencies for SSL automation (Week 1) and MySQL backup automation (Week 1-2)
- Document extension points for existing twelve-factor deployment workflow
- Include comprehensive crontab template integration and cloud-init automation
- Provide detailed technical specifications for supporting scripts and environment template updates

Critical Review Findings:
- Updated status table to reflect actual repository state (40% complete, 4/12 components)
- Identified missing files: mysql-backup.sh, crontab_utils.sh
- Clarified nginx template state (HTTP active, HTTPS commented out)
- Corrected environment template status (SSL/backup variables already present)
- Fixed all markdown linting issues and improved documentation structure

This plan provides the foundation for implementing maximum practical automation while maintaining
the existing robust twelve-factor deployment architecture.
- Create detailed implementation plan for Phase 3: Maximum Practical Application Installation Automation
- Document current state analysis with accurate status of implemented vs missing components
- Provide technical implementation details for SSL certificate automation and MySQL backup automation
- Include testing strategy with unit, integration, SSL workflow, and end-to-end testing approaches
- Define success criteria focusing on 90%+ automation with minimal manual steps
- Add risk assessment and mitigation strategies for high-risk areas
- Establish timeline and dependencies for SSL automation (Week 1) and MySQL backup automation (Week 1-2)
- Document extension points for existing twelve-factor deployment workflow
- Include comprehensive crontab template integration and cloud-init automation
- Provide detailed technical specifications for supporting scripts and environment template updates

Critical Review Findings:
- Updated status table to reflect actual repository state (40% complete, 4/12 components)
- Identified missing files: mysql-backup.sh, crontab_utils.sh
- Clarified nginx template state (HTTP active, HTTPS commented out)
- Corrected environment template status (SSL/backup variables already present)
- Fixed all markdown linting issues and improved documentation structure

This plan provides the foundation for implementing maximum practical automation while maintaining
the existing robust twelve-factor deployment architecture.
- Add comprehensive validation for SSL and backup variables in configure-env.sh
- Validate DOMAIN_NAME, CERTBOT_EMAIL (with email format check), ENABLE_SSL
- Validate ENABLE_DB_BACKUPS and BACKUP_RETENTION_DAYS (with range checks)
- Extend placeholder detection for both REPLACE_WITH_SECURE_* and REPLACE_WITH_YOUR_* patterns
- Update ADR-004 to document deployment automation configuration exception
- Update environment template comments to clarify variable purposes
- All e2e tests pass, validates 50% completion of issue #21

This implements Task 1.2 of the automation roadmap, providing foundation
for SSL certificate and backup automation scripts.
…nfiguration

- Replace dual templates (local.env.tpl, production.env.tpl) with single base.env.tpl
- Add external defaults files (local.defaults, production.defaults) for environment-specific values
- Update configure-env.sh to load defaults from files instead of hardcoded values
- Improve twelve-factor compliance with single source of truth for configuration
- Add generate-secrets command for secure production secret generation
- Update documentation and .gitignore for new file structure
- Benefits: DRY principle, easier maintenance, version-controlled defaults, no sync issues

This addresses the issue where having separate templates could lead to
synchronization bugs when adding new variables to only one template.
All environment variables now exist in one place with environment-specific
values defined in external, version-controlled defaults files.
## Database Backup Automation - FULLY COMPLETED

### ✅ Core Implementation
- **mysql-backup.sh**: Comprehensive MySQL backup script with compression, retention, logging
- **deploy-app.sh**: Integrated backup automation via setup_backup_automation() in run_stage()
- **Environment templates**: Added ENABLE_DB_BACKUPS and BACKUP_RETENTION_DAYS variables
- **Cron automation**: Automated backup scheduling integrated into deployment workflow

### ✅ Key Features Implemented
- Single-transaction MySQL dumps for data consistency
- Automatic gzip compression to save storage space
- Configurable retention policy (BACKUP_RETENTION_DAYS environment variable)
- Comprehensive error handling and logging for monitoring
- Docker Compose environment integration
- Conditional deployment based on ENABLE_DB_BACKUPS flag

### ✅ Testing & Validation
- Manual end-to-end testing with backup content verification
- Automated scheduling tested with cron job modification
- Log output validation and error handling verification
- Created comprehensive manual testing guide

### ✅ Documentation
- **database-backup-testing-guide.md**: Complete manual testing procedures
- **21-complete-application-installation-automation.md**: Updated status to reflect completion
- Progress updated from 67% to 83% (10/12 components complete)
- Phase 3 marked as fully completed with testing documentation

### 🎯 Production Ready
- Backup automation is fully functional and production-ready
- Zero manual configuration required when ENABLE_DB_BACKUPS=true
- Integrates seamlessly with existing twelve-factor deployment workflow
- All CI tests pass, shellcheck clean, comprehensive error handling

**Next Phase**: SSL certificate automation (manual scripts for admins)
@josecelano josecelano requested a review from da2ce7 July 29, 2025 16:17
@josecelano josecelano self-assigned this Jul 29, 2025
@josecelano
Copy link
Member Author

ACK bb0ba2e

@josecelano josecelano merged commit 022a931 into main Jul 29, 2025
1 check passed
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant